<?php
namespace Api\Controller;
use Think\Controller;
/**
 * 洗涤小助手接口类
 * User: 咩咩
 * Date: 2018/9/20
 * Time: 14:23
 */
class WashApiController extends Controller{
    //微信小程序-AppID(应用ID)
    protected $appid = "wx8f94abc8fb081453";
    //微信小程序-AppSecret(应用密钥)
    protected $secret = "b3647e66710f399b1e50fa7a2f4ec98e";

    //微信H5-AppID(应用ID)
    protected $wx_appid = "wx17def53be3732dcd";
    //微信H5-AppSecret(应用密钥)
    protected $wx_secret = "8c9bd3493a55891f344e7eebfab9ee39";

    //CorpID(企业ID-蓝月亮的世界)
    protected $corpid = "wx36ef368cf28caea0";
    //CorpSecret(应用密钥-消费二维码)
    protected $corpsecret = "3mCYMxjEoxyHhyGUAv1nKK-o6uPjUo-NO3Zyw_7ZoqA";

    /**
     * 卖场活动-轮播图接口
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      id:轮播图ID
     *      img_url:轮播图路径
     */
    public function activity_lunbo(){
        $db_wash_activity_lunbo = M('wash_activity_lunbo');//实例化轮播表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $wash_activity_lunbo = $db_wash_activity_lunbo->field('id,img_url')->select();

        $de_res['data'] = $wash_activity_lunbo;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 卖场活动-轮播图详情接口
     * int  id     轮播图ID
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      content:图文混排内容
     */
    public function activity_lunbo_detail(){
        $db_wash_activity_lunbo = M('wash_activity_lunbo');//实例化轮播表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_activity_lunbo_detail = $db_wash_activity_lunbo->where("id='$id'")->field('content')->find();

        $de_res['data'] = $wash_activity_lunbo_detail;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 卖场活动-门店信息接口
     * string  city    	城市
     * string  district	  区/县
     * string  brand	品牌
     * string  store_name   门店名称
     * int     page_num     第几页
     * int     page_size    每页显示条数
     * Decimal lng   起点经度
     * Decimal lat   起点纬度
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      cid:门店收藏ID
     *      store_name:门店名称
     *      address:门店地址
     *      brand:品牌
     *      banner_img_url:展示图
     *      distance:距离（千米）
     */
    public function store_info(){
        $db_wash_activity_store = M('wash_activity_store');//实例化门店信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $city = I('post.city');
        $district = I('post.district');
        $brand = I('post.brand');
        $store_name = I('post.store_name');
        $lng = I('post.lng');
        $lat = I('post.lat');

        $info = array();
        if($city){
//            $info['_string'] = "(province like '%$city%') OR (city like '%$city%')";//市
            $info['city'] = array('like', "%$city%");//市
        }else{
            $city = '广州市';//默认
            $info['city'] = array('like', "%$city%");//市
        }
        if($district){
            $info['district'] = array('like', "%$district%");//区/县
        }
        if($brand){
            $info['brand'] = array('like', "%$brand%");//品牌
        }
        if($store_name){
            $info['store_name'] = array('like', "%$store_name%");//门店名称
        }

        $page_num = I('post.page_num');
        if(!$page_num){
            $de_res['msg'] = '缺少page_num参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $page_size = I('post.page_size');
        if(!$page_size){
            $de_res['msg'] = '缺少page_size参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_activity_store = $db_wash_activity_store->where($info)->field('cid,store_name,address,brand,banner_img_url,lng,lat')->select();

        $arr = $wash_activity_store;
        if($lng != '' && $lat != ''){
            foreach ($arr as $k=>$v){
                $longitude2 = $v['lng'];
                $latitude2 = $v['lat'];

                //调用地图距离计算接口
                $map_other = new \Vendor\address\Map_other();
                $distance = $map_other->getDistance($lng, $lat, $longitude2, $latitude2, 2);

                $arr[$k]['distance'] = abs($distance - 1.15);
            }
        }

        /*按距离排序*/
        //先用array_column 多维数组按照纵向（列）取出
        $date = array_column($arr, 'distance');
        //再用array_multisort  结合array_column得到的结果对$arr进行排序
        array_multisort($date,SORT_ASC,$arr);

        //分页
        $de_res['data'] = $this->page_array($page_size,$page_num,$arr,0);

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

//        error_log($en_res."\n", 3, "test.log");//打印日志
        echo $en_res;
    }

    /**
     * 卖场活动-门店信息详情接口
     * string  cid  门店收藏编号
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      cid:门店收藏ID
     *      lng:经度
     *      lat:纬度
     *      title:活动标题
     *      activity:
     *          cid:活动ID
     *          activity_img_url:活动图
     */
    public function store_info_detail(){
        $db_wash_activity_store = M('wash_activity_store');//实例化门店信息表
        $db_wash_activity_title = M('wash_activity_title');//实例化题目管理表
        $db_wash_activity_content = M('wash_activity_content');//实例化内容管理表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $cid = I('post.cid');
        if(!$cid){
            $de_res['msg'] = '缺少cid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $store = $db_wash_activity_store->where("cid='$cid'")->field('cid,lng,lat,title_id,c_list')->find();

        $arr = array();
        $arr['lng'] = $store['lng'] - 0.00658;//数值越大 点越向左
        $arr['lat'] = $store['lat'] - 0.00558;//数值越大 点越向下

        //活动标题
        $title_id = $store['title_id'];
        $title = $db_wash_activity_title->where("cid='$title_id'")->field('title')->find();
        $arr['title'] = $title['title'];

        //活动内容
        $arr['activity'] = array();
        $c_list = json_decode($store['c_list'], true);
        foreach ($c_list as $v){
            $c = array();
            $c['cid'] = $v;
            $content = $db_wash_activity_content->where("cid='$v'")->field('activity_img_url')->find();
            $c['activity_img_url'] = $content['activity_img_url'];
            array_unshift($arr['activity'],$c);
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

//        error_log($_POST."\n", 3, "test.log");//打印日志
        echo $en_res;
    }

    /**
     * 清洁难题-产品轮播图接口
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      id:轮播图ID
     *      img_url:轮播图路径
     *      type:类型 1第三方URL 2本地URL 3图文混排 4其他
     *      url:第三方URL
     *      local_url:本地URL
     */
    public function clean_lunbo(){
        $db_wash_clean_lunbo = M('wash_clean_lunbo');//实例化轮播表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $wash_clean_lunbo = $db_wash_clean_lunbo->field('id,img_url,type,url,local_url')->select();

        $de_res['data'] = $wash_clean_lunbo;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 清洁难题-轮播图详情接口
     * int  id     轮播图ID
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      content:图文混排内容
     */
    public function clean_lunbo_detail(){
        $db_wash_clean_lunbo = M('wash_clean_lunbo');//实例化轮播表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_clean_lunbo_detail = $db_wash_clean_lunbo->where("id='$id'")->field('content')->find();

        $de_res['data'] = $wash_clean_lunbo_detail;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 清洁难题-搜索接口
     * string  title    题目
     * int     page_num     第几页
     * int     page_size    每页显示条数
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，
     *      >0错误码:
     *          400 没有收到参数
     *          401 参数错误
     * data:
     *      cid:收藏ID
     *      title:题目
     *      type:种类 1图文 2视频
     *      banner_img_url:视频/图片链接
     *      search_times:搜索次数
     */
    public function clean_info_search(){
        $db_wash_clean_clothes = M('wash_clean_clothes');//实例化衣物清洁信息表
        $db_wash_clean_kitchen = M('wash_clean_kitchen');//实例化厨房清洁信息表
        $db_wash_clean_bedroom = M('wash_clean_bedroom');//实例化卧室清洁信息表
        $db_wash_clean_bathroom = M('wash_clean_bathroom');//实例化卫浴清洁信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $title = I('post.title');
        if(!$title){
            $de_res['msg'] = '缺少title参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $page_num = I('post.page_num');
        if(!$page_num){
            $de_res['msg'] = '缺少page_num参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $page_size = I('post.page_size');
        if(!$page_size){
            $de_res['msg'] = '缺少page_size参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $arr = array();
        $info['title'] = array('like', "%$title%");
        $wash_clean_clothes = $db_wash_clean_clothes->where($info)->field('cid,title,type,banner_img_url,search_times')->select();
        foreach ($wash_clean_clothes as $v){
            array_push($arr,$v);
        }
        $wash_clean_kitchen = $db_wash_clean_kitchen->where($info)->field('cid,title,type,banner_img_url,search_times')->select();
        foreach ($wash_clean_kitchen as $v){
            array_push($arr,$v);
        }
        $wash_clean_bedroom = $db_wash_clean_bedroom->where($info)->field('cid,title,type,banner_img_url,search_times')->select();
        foreach ($wash_clean_bedroom as $v){
            array_push($arr,$v);
        }
        $wash_clean_bathroom = $db_wash_clean_bathroom->where($info)->field('cid,title,type,banner_img_url,search_times')->select();
        foreach ($wash_clean_bathroom as $v){
            array_push($arr,$v);
        }

        /*数组排序*/
        //先用array_column 多维数组按照纵向（列）取出
        $date = array_column($arr, 'search_times');
        //再用array_multisort  结合array_column得到的结果对$arr进行排序
        array_multisort($date,SORT_DESC,$arr);

        //分页
        $de_res['data'] = $this->page_array($page_size,$page_num,$arr,0);

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 清洁难题-置顶信息接口
     * int     kind    类型（1衣物清洁 2厨房清洁 3卧室清洁 4卫浴清洁）
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，
     *      >0错误码:
     *          400 没有收到参数
     *          401 参数错误
     * data:
     *      picture:
     *          cid:信息收藏ID
     *          title:题目
     *          banner_img_url:视频/图片链接
     *      video:
     *          cid:信息收藏ID
     *          title:题目
     *          banner_img_url:视频/图片链接
     */
    public function clean_top_info(){
        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $kind = I('post.kind');
        if(!$kind){
            $de_res['msg'] = '缺少kind参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        if ($kind == 1){ //1衣物清洁
            $db_wash_clean = M('wash_clean_clothes');//实例化衣物清洁信息表
        }elseif ($kind == 2){ //2厨房清洁
            $db_wash_clean = M('wash_clean_kitchen');//实例化厨房清洁信息表
        }elseif ($kind == 3){ //3卧室清洁
            $db_wash_clean = M('wash_clean_bedroom');//实例化卧室清洁信息表
        }elseif ($kind == 4){ //4卫浴清洁
            $db_wash_clean = M('wash_clean_bathroom');//实例化卫浴清洁信息表
        }else{
            $de_res['msg'] = 'kind参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //图文
        $wash_clean_picture = $db_wash_clean->where("type=1 AND top=1")->order('search_times DESC,time DESC')->field('cid,title,banner_img_url')->limit(4)->select();
        //视频
        $wash_clean_video = $db_wash_clean->where("type=2 AND top=1")->order('search_times DESC,time DESC')->field('cid,title,banner_img_url')->limit(4)->select();

        //分组
        $de_res['data']['picture'] = $wash_clean_picture;
        $de_res['data']['video'] = $wash_clean_video;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 清洁难题-更多信息接口
     * int     kind    类型（1衣物清洁 2厨房清洁 3卧室清洁 4卫浴清洁）
     * int     type    种类 1图文 2视频
     * int     page_num     第几页
     * int     page_size    每页显示条数
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，
     *      >0错误码:
     *          400 没有收到参数
     *          401 参数错误
     * data:
     *      cid:信息收藏ID
     *      title:题目
     *      banner_img_url:视频/图片链接
     */
    public function clean_info(){
        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $kind = I('post.kind');
        if(!$kind){
            $de_res['msg'] = '缺少kind参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $type = I('post.type');
        if(!$type){
            $de_res['msg'] = '缺少type参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        if($type != 1 && $type != 2){
            $de_res['msg'] = 'type参数错误';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $page_num = I('post.page_num');
        if(!$page_num){
            $de_res['msg'] = '缺少page_num参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $page_size = I('post.page_size');
        if(!$page_size){
            $de_res['msg'] = '缺少page_size参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        if ($kind == 1){ //1衣物清洁
            $db_wash_clean = M('wash_clean_clothes');//实例化衣物清洁信息表
        }elseif ($kind == 2){ //2厨房清洁
            $db_wash_clean = M('wash_clean_kitchen');//实例化厨房清洁信息表
        }elseif ($kind == 3){ //3卧室清洁
            $db_wash_clean = M('wash_clean_bedroom');//实例化卧室清洁信息表
        }elseif ($kind == 4){ //4卫浴清洁
            $db_wash_clean = M('wash_clean_bathroom');//实例化卫浴清洁信息表
        }else{
            $de_res['msg'] = 'kind参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_clean = $db_wash_clean->where("type='$type' AND top=0")->order('search_times DESC,time DESC')->field('cid,title,banner_img_url')->select();
//        error_log('wash_clean='.json_encode($wash_clean, 320)."\n", 3, "test.log");//打印日志

        //分页
        $de_res['data'] = $this->page_array($page_size,$page_num,$wash_clean,0);

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 清洁难题-信息详情接口
     * string  cid  信息收藏ID
     * string  uid  用户ID
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      cid:收藏编号
     *      title:题目
     *      content:内容
     *      banner_img_url:封面图片路径
     *      video_url:视频路径（若是图文详情则该字段为空）
     *      search_times:浏览次数
     *      collection:是否收藏 1收藏 0未收藏
     *      datetime:时间
     */
    public function clean_info_detail(){
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $uid = I('post.uid');
        $user = $db_wash_user->where("uid='$uid'")->field('c_list')->find();
        if($user){
            $c_list = json_decode($user['c_list']);
        }else{
            $c_list = '';
        }

        $cid = I('post.cid');
        if(!$cid){
            $de_res['msg'] = '缺少cid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //获取表ID
        $type = substr($cid,-2);
//        error_log('type='.$type."\n", 3, "test.log");//打印日志

        if ($type == 1){ //1衣物清洁
            $db_wash_clean = M('wash_clean_clothes');//实例化衣物清洁信息表
        }elseif ($type == 2){ //2厨房清洁
            $db_wash_clean = M('wash_clean_kitchen');//实例化厨房清洁信息表
        }elseif ($type == 3){ //3卧室清洁
            $db_wash_clean = M('wash_clean_bedroom');//实例化卧室清洁信息表
        }elseif ($type == 4){ //4卫浴清洁
            $db_wash_clean = M('wash_clean_bathroom');//实例化卫浴清洁信息表
        }else{
            $de_res['msg'] = 'cid解析参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_clean_detail = $db_wash_clean->where("cid='$cid'")->field('cid,title,content,banner_img_url,video_url,search_times,datetime')->find();
        $arr = $wash_clean_detail;

        $arr['collection'] = 0;//初始化为未收藏
        if($c_list != ''){
            foreach($c_list as $c){
                if($arr['cid'] == $c){
                    $arr['collection'] = 1;
                }
            }
        }

        $arr['search_times'] += 1;
        $info['search_times'] = $arr['search_times'];
        $edit_wash_clean = $db_wash_clean->where("cid='$cid'")->setField($info);
        if(!$edit_wash_clean){
            $de_res['msg'] = '搜索次数更新失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);
//        error_log('en_res='.$en_res."\n", 3, "test.log");//打印日志

        echo $en_res;
    }

    /**
     * 用量计算接口
     * string  weight  总重量
     * string  wid_list  洗涤功能编号列表(json数组)
     * string  did_list  去污功能编号列表(json数组)
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *		pre:洗涤必备
     *          id:产品编号
	 *			product_name：产品名
	 *			product_url：图片链接
	 *			dose：计算用量
	 *			dosage：推荐用量
	 *			recommend：推荐指数
	 *		wash:洗涤搭配
     *          id:产品编号
	 *			product_name：产品名
	 *			label：标签
	 *			product_url：图片链接
	 *		dirt:去污必备
     *          id:产品编号
     *			product_name：产品名
     *			label：标签
     *			product_url：图片链接
     */
    public function calculation(){
        $db_wash_calculation_clothes = M('wash_calculation_clothes');//实例化衣物信息表
        $db_wash_calculation_product = M('wash_calculation_product');//实例化产品信息表
        $db_wash_calculation_function = M('wash_calculation_function');//实例化洗涤功能表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $weight = I('post.weight');
        if(!$weight){
            $de_res['msg'] = '缺少weight参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $wid_list = I('post.wid_list');
        if(!$wid_list){
            $de_res['msg'] = '缺少wid_list参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $wid_list = json_decode($wid_list, true);
        if(!is_array($wid_list)){
            $de_res['msg'] = 'wid_list参数错误';
            $de_res['error'] = 402;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        if(count($wid_list) == 0){
            $de_res['msg'] = 'wid_list参数为空';
            $de_res['error'] = 402;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $did_list = I('post.did_list');

        $arr = array('pre'=>array(),'wash'=>array(),'dirt'=>array());

        /*基础参数*/
        $base = $db_wash_calculation_clothes->where("belong_id=0")->field('weight,dosage_list')->find();
        $base_weight = $base['weight'];//基础重量g
        $dosage_list = json_decode($base['dosage_list'], true);//基础用量g

        /*洗涤必备计算*/
        $p_first = 0;//洗衣液选择优先参数 默认没有优先
        $p_list = array();
        $w_list = array();
        foreach ($wid_list as $wid){
            //判断使用哪种洗衣液
            $pre_first = $db_wash_calculation_function->where("id='$wid'")->field('p_first,p_list,w_list')->find();
            if($pre_first['p_first'] == 1){
                $p_first = 1;
                $p_list = json_decode($pre_first['p_list'], true);
            }

            //统计使用到的洗涤搭配产品
            $wash_list = json_decode($pre_first['w_list'], true);
            if(is_array($wash_list)){
                foreach ($wash_list as $wash_p){
                    array_push($w_list,$wash_p);
                }
            }else{
                $de_res['msg'] = 'wash_list数据类型错误';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }

        if($p_first == 0){
            $wash_not_first = $db_wash_calculation_function->where("belong_id=0")->field('p_list')->select();
            $p_list = json_decode($wash_not_first[0]['p_list'], true);
        }

        if(is_array($p_list)){
            foreach($p_list as $k=>$p){
                $pid = $p[array_rand($p)];
                if(!$pid){
                    $de_res['msg'] = '洗涤必备参数异常';
                    $de_res['error'] = 403;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
                //判断该产品是否设置了基础计量单位
                if(isset($dosage_list[$pid])){
                    $p_arr = array();
                    $product = $db_wash_calculation_product->where("id='$pid'")->field('id,product_name,label,product_url')->find();
                    $p_arr['id'] = $product['id'];
                    $p_arr['product_name'] = $product['product_name'];
                    $p_arr['label'] = $product['label'];
                    $p_arr['product_url'] = $product['product_url'];

                    $dosage = $dosage_list[$pid];
                    $dose = $weight / $base_weight * $dosage;
                    if(floor($dose) == $dose){
                        $p_arr['dose'] = (string)number_format($dose,1); //当为整数，保留一位小数
                    }else{
                        $p_arr['dose'] = (string)round($dose, 2); //四舍五入保留两位小数
                    }

                    //判断至尊和普通洗衣液使用规格
                    if($k == 0){
                        //判断推荐用量
                        if($weight > 0 and $weight <= 1200){
                            $p_arr['dosage'] = '1泵';
                        }elseif ($weight > 1200 and $weight <= 2400){
                            $p_arr['dosage'] = '2泵';
                        }elseif ($weight > 2400 and $weight <= 3600){
                            $p_arr['dosage'] = '3泵';
                        }else{
                            $de_res['msg'] = '超过可计算范围';
                            $de_res['error'] = 404;
                            $en_res = json_encode($de_res, 320);
                            exit($en_res);
                        }
                    }elseif ($k == 1){
                        //判断推荐用量
                        if($weight > 0 and $weight <= 1200){
                            $p_arr['dosage'] = '半盖左右';
                        }elseif ($weight > 1200 and $weight <= 2400){
                            $p_arr['dosage'] = '一盖左右';
                        }elseif ($weight > 2400 and $weight <= 3600){
                            $p_arr['dosage'] = '1.5盖左右';
                        }else{
                            $de_res['msg'] = '超过可计算范围';
                            $de_res['error'] = 404;
                            $en_res = json_encode($de_res, 320);
                            exit($en_res);
                        }
                    }

                    array_push($arr['pre'], $p_arr);
                }else{
                    $de_res['msg'] = '缺少计算用量基数';
                    $de_res['error'] = 403;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }

            /*洗涤搭配计算*/
            //数组去重
            $w_list = array_unique($w_list);
            $w_list = array_values($w_list);

            //构成洗涤搭配产品数组
            foreach($w_list as $w_id){
                $w_arr = array();
                $w_product = $db_wash_calculation_product->where("id='$w_id'")->field('id,product_name,label,product_url')->find();
                $w_arr['id'] = $w_product['id'];
                $w_arr['product_name'] = $w_product['product_name'];
                $w_arr['label'] = $w_product['label'];
                $w_arr['product_url'] = $w_product['product_url'];

                array_push($arr['wash'], $w_arr);
            }
        }else{
            $de_res['msg'] = 'p_list数据类型错误';
            $de_res['error'] = 402;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        /*去污必备计算*/
        $d_list = array();
        if(strlen($did_list) != 0){
            $did_list = json_decode($did_list, true);
            if(is_array($did_list)){
                foreach ($did_list as $did){
                    //统计使用到的去污必备产品
                    $dirt = $db_wash_calculation_function->where("id='$did'")->field('d_list')->find();
                    $dirt_list = json_decode($dirt['d_list'], true);
                    if(is_array($dirt_list)){
                        foreach ($dirt_list as $dirt_id){
                            array_push($d_list,$dirt_id);
                        }
                    }else{
                        $de_res['msg'] = 'dirt_list数据类型错误';
                        $de_res['error'] = 402;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                }

                //数组去重
                $d_list = array_unique($d_list);
                $d_list = array_values($d_list);

                //构成去污必备产品数组
                foreach($d_list as $d_id){
                    $d_arr = array();
                    $d_product = $db_wash_calculation_product->where("id='$d_id'")->field('id,product_name,label,product_url')->find();
                    $d_arr['id'] = $d_product['id'];
                    $d_arr['product_name'] = $d_product['product_name'];
                    $d_arr['label'] = $d_product['label'];
                    $d_arr['product_url'] = $d_product['product_url'];

                    array_push($arr['dirt'], $d_arr);
                }
            }else{
                $de_res['msg'] = 'did_list数据类型错误';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);
//        error_log('$en_res='.$en_res."\n", 3, "test.log");//打印日志
        echo $en_res;
    }

    /**
     * 用量计算-产品使用方法接口
     * string pid 产品编号
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      id:产品编号
     *      product_name:产品名称
     *      use_method:使用方法
     *      product_url:产品图片链接
     */
    public function calculation_product_detail(){
        $db_wash_calculation_product = M('wash_calculation_product');//实例化产品信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $pid = I('post.pid');
        if(!$pid){
            $de_res['msg'] = '缺少pid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $wash_calculation_product = $db_wash_calculation_product->where("id='$pid'")->field('id,product_name,use_method,product_url')->find();

        $de_res['data'] = $wash_calculation_product;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 用量计算-衣物列表接口
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      name:一级菜单名
     *      list:一级菜单列表
     *          name:二级菜单名
     *          list:二级菜单列表
     *              id:衣物编号
     *              name:衣物名
     *              weight:衣物重量g
     *              img_url:图片链接
     *              value:0
     */
    public function calculation_clothes(){
        $db_wash_calculation_clothes = M('wash_calculation_clothes');//实例化衣物信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $arr = array();

        $clothes_one_level = $db_wash_calculation_clothes->where("belong_id=1")->field('id,name')->select();
        foreach($clothes_one_level as $one_level){
            $one_array = array();
            $one_array['name'] = $one_level['name'];
            $one_array['list'] = array();

            $one_level_id = $one_level['id'];
            $clothes_two_level = $db_wash_calculation_clothes->where("belong_id='$one_level_id'")->field('id,name')->select();
            foreach ($clothes_two_level as $two_level){
                $two_array = array();
                $two_array['name'] = $two_level['name'];
                $two_array['list'] = array();

                $two_level_id = $two_level['id'];
                $clothes_three_level = $db_wash_calculation_clothes->where("belong_id='$two_level_id'")->field('id,name,weight,img_url')->select();
                foreach($clothes_three_level as $three_level){
                    $three_array = array();
                    $three_array['id'] = $three_level['id'];
                    $three_array['name'] = $three_level['name'];
                    $three_array['weight'] = $three_level['weight'];
                    $three_array['img_url'] = $three_level['img_url'];
                    $three_array['value'] = 0;

                    array_push($two_array['list'],$three_array);
                }
                array_push($one_array['list'],$two_array);
            }
            array_push($arr,$one_array);
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 用量计算-洗涤功能列表接口
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      name:一级菜单名
     *      list:一级菜单列表
     *          id:功能编号
     *          name:功能名
     *          img_url:图片链接
     *          checked:false(布尔值)
     */
    public function calculation_function(){
        $db_wash_calculation_function = M('wash_calculation_function');//实例化洗涤功能表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $arr = array();

        $function_one_level = $db_wash_calculation_function->where("belong_id=0")->order('id DESC')->field('id,name')->select();
        foreach($function_one_level as $one_level){
            $one_array = array();
            $one_array['name'] = $one_level['name'];
            $one_array['list'] = array();

            $one_level_id = $one_level['id'];
            $function_two_level = $db_wash_calculation_function->where("belong_id='$one_level_id'")->order('id ASC')->field('id,name,img_url')->select();
            foreach ($function_two_level as $two_level){
                $two_array = array();
                $two_array['id'] = $two_level['id'];
                $two_array['name'] = $two_level['name'];
                $two_array['img_url'] = $two_level['img_url'];
                $two_array['checked'] = false;

                array_push($one_array['list'],$two_array);
            }
            array_push($arr,$one_array);
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 收藏接口
     * int     type  类型（1收藏 2取消）
     * string  uid   用户ID
     * string  cid   收藏编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function collection(){
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $type = I('post.type');
        if(!$type){
            $de_res['msg'] = '缺少type参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        if($type != 1 && $type != 2){
            $de_res['msg'] = 'type参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $uid = I('post.uid');
        if(!$uid){
            $de_res['msg'] = '缺少uid参数';
            $de_res['error'] = 11001;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $user = $db_wash_user->where("uid='$uid'")->find();
        $c_list = json_decode($user['c_list']);

        $cid = I('post.cid');
        if(!$cid){
            $de_res['msg'] = '缺少cid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        if($type == 1){
            if(!in_array($cid,$c_list)){
                array_unshift($c_list, $cid);
                $info['c_list'] = json_encode($c_list, true);
                $edit_wash_user = $db_wash_user->where("uid='$uid'")->setField($info);
                if($edit_wash_user){
                    $de_res['msg'] = '收藏成功';
                    $de_res['error'] = 0;
                }else{
                    $de_res['msg'] = '收藏失败';
                    $de_res['error'] = 402;
                }
            }else{
                $de_res['msg'] = '收藏重复';
                $de_res['error'] = 403;
            }
        }elseif ($type == 2){
            if(in_array($cid,$c_list)) {
                $c_key = array_search($cid, $c_list);//搜索某个键值，并返回对应的键名
                unset($c_list[$c_key]);//删除数组元素
                sort($c_list);//数组键名重新排序

                $info['c_list'] = json_encode($c_list, true);
//            error_log('c_list='.$info['c_list']."\n", 3, "test.log");//打印日志
                $edit_wash_user = $db_wash_user->where("uid='$uid'")->setField($info);
                if ($edit_wash_user) {
                    $de_res['msg'] = '取消成功';
                    $de_res['error'] = 0;
                } else {
                    $de_res['msg'] = '取消失败';
                    $de_res['error'] = 402;
                }
            }else{
                $de_res['msg'] = '取消重复';
                $de_res['error'] = 403;
            }
        }else{
            $de_res['msg'] = 'type参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 收藏列表接口
     * string  uid   用户ID
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      cid:收藏编号
     *      type:类型 1图文 2视频 3店铺
     *      banner_img_url:图片链接
     *      title:题目
     *      datetime:日期
     */
    public function collection_list(){
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $uid = I('post.uid');
        if(!$uid){
            $de_res['msg'] = '缺少uid参数';
            $de_res['error'] = 11001;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $user = $db_wash_user->where("uid='$uid'")->find();
        $c_list = json_decode($user['c_list']);
//        error_log('c_list='.$user['c_list']."\n", 3, "test.log");//打印日志

        $arr = array();
        if(!empty($c_list)) {
            foreach ($c_list as $cid) {
                //获取表ID
                $type = substr($cid, -2);
//                error_log('cid='.$cid."\n", 3, "test.log");//打印日志
//                error_log('type='.$type."\n", 3, "test.log");//打印日志

                //调用表名配置接口
                $config = new \Vendor\config\Config();
                $table_name = $config->wash_table($type);

                $db_wash = M($table_name);//实例化对应表
                $wash = $db_wash->where("cid='$cid'")->field('cid,type,banner_img_url,title,datetime')->find();
                if(!empty($wash)) {
                    array_push($arr, $wash);
                }
            }
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 评论-列表接口
     * string  uid  用户编号
     * string  cid  收藏编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      id:评论编号
     *      uid:用户ID
     *      nickName:用户昵称
     *      avatarUrl:头像链接
     *      content:评论内容
     *      praise_count:点赞数
     *      reply_count:回复总数
     *      time:时间戳
     *      datetime:时间
     *      report:是否举报过 1已举报 0未举报（没有uid）
     *      praise:是否点赞过 1已点赞 0未点赞（没有uid）
     */
    public function comment_list(){
        $db_wash_comment = M('wash_comment');//实例化评论列表
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $uid = I('post.uid');

        $cid = I('post.cid');
        if(!$cid){
            $de_res['msg'] = '缺少cid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $info = array();
        if($cid){
            $info['cid'] = $cid;
        }
        $info['status'] = 1;
        $wash_comment = $db_wash_comment->where($info)->order('time DESC')->field('id,uid,content,praise_count,reply_count,time,datetime')->select();
        $arr = array();

        if($uid){
            $user = $db_wash_user->where("uid='$uid'")->field('comment_report_list,comment_praise_list')->find();
            if(!$user){
                $de_res['msg'] = '未查询到用户信息';
                $de_res['error'] = 403;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
            $comment_report_list = json_decode($user['comment_report_list'], true);
            $comment_praise_list = json_decode($user['comment_praise_list'], true);

            foreach($wash_comment as $v){
                //判断登录用户是否已经举报过
                if(in_array($v['id'],$comment_report_list)){
                    $v['report'] = 1;
                }else{
                    $v['report'] = 0;
                }

                //判断登录用户是否已经点赞过
                if(in_array($v['id'],$comment_praise_list)){
                    $v['praise'] = 1;
                }else{
                    $v['praise'] = 0;
                }

                $info_user['uid'] = $v['uid'];
                $wash_user = $db_wash_user->where($info_user)->field('nickName,avatarUrl')->find();
                $v['nickName'] = $wash_user['nickName'];
                $v['avatarUrl'] = $wash_user['avatarUrl'];
                $v['datetime'] = date('Y/m/d H:i:s',$v['time']);
                array_push($arr,$v);
            }
        }else{
            foreach($wash_comment as $v){
                $v['report'] = 0;
                $v['praise'] = 0;

                $info_user['uid'] = $v['uid'];
                $wash_user = $db_wash_user->where($info_user)->field('nickName,avatarUrl')->find();
                $v['nickName'] = $wash_user['nickName'];
                $v['avatarUrl'] = $wash_user['avatarUrl'];
                $v['datetime'] = date('Y/m/d H:i:s',$v['time']);
                array_push($arr,$v);
            }
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 评论-新增接口
     * string  cid  收藏编号
     * string  uid  用户ID
     * string  content  评论内容
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function comment_add(){
        $db_wash_comment = M('wash_comment');//实例化评论列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $cid = I('post.cid');
        if(!$cid){
            $de_res['msg'] = '缺少cid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $uid = I('post.uid');
        if(!$uid){
            $de_res['msg'] = '缺少uid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $content = I('post.content');
        if(!$content){
            $de_res['msg'] = '缺少content参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $info = array();
        //调用配置接口
        $config = new \Vendor\config\Config();
        //生成唯一标识编号
        $info['cr_id'] = $config->create_unique_id('wash_comment');

        $info['cid'] = $cid;
        $info['uid'] = $uid;
        $info['content'] = $content;
        $info['status'] = 1;
        $info['report_count'] = 0;
        $info['praise_count'] = 0;
        $info['reply_count'] = 0;
        $info['time'] = time();
        $info['datetime'] = date('Y-m-d H:i:s');
        $add_wash_comment = $db_wash_comment->data($info)->add();
        if(!$add_wash_comment){
            $de_res['msg'] = '评论写入失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        unset($info['content']);//去除内容筛选条件 防止奇葩输入表情时解析不出来报错
        $wash_comment = $db_wash_comment->where($info)->order('id DESC')->field('id')->find();
        if(!$wash_comment){
            $de_res['msg'] = '评论ID获取失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['msg'] = '评论成功!';
        $de_res['data']['id'] = $wash_comment['id'];

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 评论-举报接口
     * string  uid  用户ID
     * string  id  评论编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function comment_report_add(){
        $db_wash_comment = M('wash_comment');//实例化评论列表
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $uid = I('post.uid');
        if(!$uid){
            $de_res['msg'] = '缺少uid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $user = $db_wash_user->where("uid='$uid'")->field('comment_report_list')->find();
        if(!$user){
            $de_res['msg'] = '未查询到用户信息';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $comment_report_list = json_decode($user['comment_report_list'], true);

        //判断登录用户是否已经举报过
        if(in_array($id,$comment_report_list)){
            $de_res['msg'] = '已举报,请勿重复举报!';
            $de_res['error'] = 300;
        }else{
            array_push($comment_report_list, $id);
            $info['comment_report_list'] = json_encode($comment_report_list, true);
            $edit_wash_user = $db_wash_user->where("uid='$uid'")->setField($info);
            if(!$edit_wash_user){
                $de_res['msg'] = '同步到举报列表失败';
                $de_res['error'] = 403;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }

            //数加1
            $add_wash_comment = $db_wash_comment->where("id='$id'")->setInc('report_count');
            if(!$add_wash_comment){
                $de_res['msg'] = '举报总数更新失败';
                $de_res['error'] = 403;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }

            $de_res['msg'] = '举报成功!';
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 评论-点赞接口
     * int     praiseType  类型（1点赞 2取消）
     * string  uid  用户ID
     * string  id  回复编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function comment_praise_add(){
        $db_wash_comment = M('wash_comment');//实例化评论列表
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $type = I('post.praiseType');
        if(!$type){
            $de_res['msg'] = '缺少type参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $uid = I('post.uid');
        if(!$uid){
            $de_res['msg'] = '缺少uid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $user = $db_wash_user->where("uid='$uid'")->field('comment_praise_list')->find();
        if(!$user){
            $de_res['msg'] = '未查询到用户信息';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $comment_praise_list = json_decode($user['comment_praise_list'], true);

        if($type == 1){
            if(in_array($id,$comment_praise_list)){
                $de_res['msg'] = '点赞操作重复';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }else{
                array_push($comment_praise_list, $id);
                $info['comment_praise_list'] = json_encode($comment_praise_list, true);
                $edit_wash_user = $db_wash_user->where("uid='$uid'")->setField($info);
                if(!$edit_wash_user){
                    $de_res['msg'] = '同步到点赞列表失败';
                    $de_res['error'] = 403;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }

                //数加1
                $edit_wash_comment = $db_wash_comment->where("id='$id'")->setInc('praise_count');
                if(!$edit_wash_comment){
                    $de_res['msg'] = '点赞总数更新失败';
                    $de_res['error'] = 403;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }

                $de_res['msg'] = '点赞成功!';
            }
        }elseif ($type == 2){
            if(in_array($id,$comment_praise_list)){
                $c_p_key = array_search($id, $comment_praise_list);//搜索某个键值，并返回对应的键名
                unset($comment_praise_list[$c_p_key]);//删除数组元素
                sort($comment_praise_list);//数组键名重新排序

                $info['comment_praise_list'] = json_encode($comment_praise_list, true);
                $edit_wash_user = $db_wash_user->where("uid='$uid'")->setField($info);
                if(!$edit_wash_user){
                    $de_res['msg'] = '同步到取消列表失败';
                    $de_res['error'] = 403;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }

                //数减1
                $add_wash_comment = $db_wash_comment->where("id='$id'")->setDec('praise_count');
                if(!$add_wash_comment){
                    $de_res['msg'] = '取消总数更新失败';
                    $de_res['error'] = 403;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }

                $de_res['msg'] = '取消成功!';
            }else{
                $de_res['msg'] = '取消操作重复';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }else{
            $de_res['msg'] = 'type参数错误';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 回复-列表接口
     * string  comment_id  评论编号（comment_list评论列表接口返回值中的id）
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      comment:
     *          id:评论编号
     *          uid:用户ID
     *          nickName:用户昵称
     *          avatarUrl:头像链接
     *          content:评论内容
     *          praise_count:点赞数
     *          reply_count:回复总数
     *          time:时间戳
     *          datetime:时间
     *      reply:
     *          id:回复编号
     *          uid:用户ID
     *          nickName:用户昵称
     *          avatarUrl:头像链接
     *          reply_uid:回复的用户ID
     *          reply_nickName:回复的用户昵称
     *          reply_avatarUrl:回复的头像链接
     *          content:评论内容
     *          praise_count:点赞数
     *          time:时间戳
     *          datetime:时间
     */
    public function reply_list(){
        $db_wash_reply = M('wash_reply');//实例化回复列表
        $db_wash_user = M('wash_user');//实例化用户信息表
        $db_wash_comment = M('wash_comment');//实例化评论列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $comment_id = I('post.comment_id');
        if(!$comment_id){
            $de_res['msg'] = '缺少comment_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //获取评论信息
        $wash_comment = $db_wash_comment->where("id='$comment_id'")->field('id,uid,content,praise_count,reply_count,time,datetime')->find();
        $comment_uid = $wash_comment['uid'];
        $wash_user = $db_wash_user->where("uid='$comment_uid'")->field('nickName,avatarUrl')->find();
        $de_res['data']['comment'] = $wash_comment;
        $de_res['data']['comment']['nickName'] = $wash_user['nickName'];
        $de_res['data']['comment']['avatarUrl'] = $wash_user['avatarUrl'];
        $de_res['data']['comment']['datetime'] = date('Y/m/d H:i:s',$wash_comment['time']);

        $info = array();
        if($comment_id){
            $info['comment_id'] = $comment_id;
        }
        $info['status'] = 1;
        $wash_reply = $db_wash_reply->where($info)->order('time ASC')->field('id,uid,reply_uid,content,praise_count,time,datetime')->select();
        $arr = array();
        foreach($wash_reply as $v){
            $info_user['uid'] = $v['uid'];
            $wash_user = $db_wash_user->where($info_user)->field('nickName,avatarUrl')->find();
            $v['nickName'] = $wash_user['nickName'];
            $v['avatarUrl'] = $wash_user['avatarUrl'];

            $info_reply_user['uid'] = $v['reply_uid'];
            $wash_reply_user = $db_wash_user->where($info_reply_user)->field('nickName,avatarUrl')->find();
            $v['reply_nickName'] = $wash_reply_user['nickName'];
            $v['reply_avatarUrl'] = $wash_reply_user['avatarUrl'];
            $v['datetime'] = date('Y/m/d H:i:s',$v['time']);
            array_push($arr,$v);
        }

        $de_res['data']['reply'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 回复-新增接口
     * string  comment_id  评论编号
     * string  uid  用户ID
     * string  reply_uid  回复用户ID
     * string  content  评论内容
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function reply_add(){
        $db_wash_reply = M('wash_reply');//实例化回复列表
        $db_wash_comment = M('wash_comment');//实例化评论列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $comment_id = I('post.comment_id');
        if(!$comment_id){
            $de_res['msg'] = '缺少comment_id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $uid = I('post.uid');
        if(!$uid){
            $de_res['msg'] = '缺少uid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $reply_uid = I('post.reply_uid');
        if(!$reply_uid){
            $de_res['msg'] = '缺少reply_uid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $content = I('post.content');
        if(!$content){
            $de_res['msg'] = '缺少content参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $info = array();
        //调用配置接口
        $config = new \Vendor\config\Config();
        //生成唯一标识编号
        $info['cr_id'] = $config->create_unique_id('wash_reply');

        $info['comment_id'] = $comment_id;
        $info['uid'] = $uid;
        $info['reply_uid'] = $reply_uid;
        $info['content'] = $content;
        $info['status'] = 1;
        $info['report_count'] = 0;
        $info['praise_count'] = 0;
        $info['time'] = time();
        $info['datetime'] = date('Y-m-d H:i:s');
        $add_wash_reply = $db_wash_reply->data($info)->add();
        if(!$add_wash_reply){
            $de_res['msg'] = '回复写入失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //回复数加1
        $add_wash_comment = $db_wash_comment->where("id='$comment_id'")->setInc('reply_count');
        if(!$add_wash_comment){
            $de_res['msg'] = '回复数更新失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        unset($info['content']);//去除内容筛选条件 防止奇葩输入表情时解析不出来报错
        $wash_reply = $db_wash_reply->where($info)->order('id DESC')->field('id')->find();
        if(!$wash_reply){
            $de_res['msg'] = '回复ID获取失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //消息推送
        $info_msg = array();
        $info_msg['cr_id'] = $info['cr_id'];
        $info_msg['comment_id'] = $comment_id;
        $info_msg['uid'] = $uid;
        $info_msg['reply_uid'] = $reply_uid;
        $info_msg['content'] = $content;
        $info_msg['time'] = $info['time'];
        $info_msg['datetime'] = $info['datetime'];
        $message_add = $this->message_add($info_msg);
        if($message_add != 200){
            $de_res['msg'] = '消息推送失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['msg'] = '回复成功!';
        $de_res['data']['id'] = $wash_reply['id'];

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 回复-举报接口
     * string  id  回复编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function reply_report_add(){
        $db_wash_reply = M('wash_reply');//实例化回复列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //数加1
        $add_wash_reply = $db_wash_reply->where("id='$id'")->setInc('report_count');
        if(!$add_wash_reply){
            $de_res['msg'] = '举报失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['msg'] = '举报成功!';

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 回复-点赞接口
     * string  id  回复编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function reply_praise_add(){
        $db_wash_reply = M('wash_reply');//实例化回复列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //数加1
        $add_wash_reply = $db_wash_reply->where("id='$id'")->setInc('praise_count');
        if(!$add_wash_reply){
            $de_res['msg'] = '点赞失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['msg'] = '点赞成功!';

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 消息-列表接口
     * string  reply_uid  接收消息的用户ID
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      id:消息ID
     *      comment_id:评论ID
     *      uid:用户ID
     *      nickName:用户昵称
     *      avatarUrl:头像链接
     *      reply_uid:回复的用户ID
     *      reply_nickName:回复的用户昵称
     *      reply_avatarUrl:回复的头像链接
     *      content:评论内容
     *      time:时间戳
     *      datetime:时间
     */
    public function message_list(){
        $db_wash_message = M('wash_message');//实例化消息表
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $reply_uid = I('post.reply_uid');
        if(!$reply_uid){
            $de_res['msg'] = '缺少reply_uid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_message = $db_wash_message->where("reply_uid='$reply_uid'")->order('time DESC')->field('id,cr_id,comment_id,uid,reply_uid,content,time,datetime')->select();
        $arr = array();
        if($wash_message){
            foreach($wash_message as $v){
                $info_user['uid'] = $v['uid'];
                $wash_user = $db_wash_user->where($info_user)->field('nickName,avatarUrl')->find();
                $v['nickName'] = $wash_user['nickName'];
                $v['avatarUrl'] = $wash_user['avatarUrl'];

                $info_reply_user['uid'] = $v['reply_uid'];
                $wash_reply_user = $db_wash_user->where($info_reply_user)->field('nickName,avatarUrl')->find();
                $v['reply_nickName'] = $wash_reply_user['nickName'];
                $v['reply_avatarUrl'] = $wash_reply_user['avatarUrl'];
                $v['datetime'] = date('Y/m/d H:i:s',$v['time']);
                array_push($arr,$v);
            }
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 消息-新增
     * array  info  条件数组
     */
    public function message_add($info){
        $db_wash_message = M('wash_message');//实例化消息表

        $add_wash_message = $db_wash_message->data($info)->add();
        if(!$add_wash_message){
            return 403;
        }else{
            return 200;
        }
    }

    /**
     * 消息-清除
     * string  id  消息ID
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function message_del(){
        $db_wash_message = M('wash_message');//实例化消息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $id = I('post.id');
        if(!$id){
            $de_res['msg'] = '缺少id参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $del_wash_message = $db_wash_message->where("id='$id'")->delete();
        if(!$del_wash_message){
            $de_res['msg'] = '消息清除失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['msg'] = '消息清除成功!';

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * 小程序-授权登录
     */
    public function getUserInfo(){
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $code = I('post.code');
//        error_log('code='.$code."\n", 3, "test.log");//打印日志

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appid."&secret=".$this->secret."&js_code=".$code."&grant_type=authorization_code";
        $str = $this->http_curl($url);

        $session_key = $str['session_key'];
//        error_log('session_key='.$session_key."\n", 3, "test.log");//打印日志

        /*校验*/
        $rawData = I('post.rawData');
        $signature = I('post.signature');

        $encryptedData = I('post.encryptedData');
//        error_log('encryptedData='.$encryptedData."\n", 3, "test.log");//打印日志
        $iv = I('post.iv');
//        error_log('iv='.$iv."\n", 3, "test.log");//打印日志

        $errCode = $this->decryptData($encryptedData, $iv, $session_key, $data);
//        error_log('errCode='.$errCode."\n", 3, "test.log");//打印日志
        if ($errCode == 0) {
//            print($data . "\n");
//            error_log('data='.$data."\n", 3, "test.log");//打印日志

            $data = json_decode($data, true);
            $unionId = $data['unionId'];
            $wash_user = $db_wash_user->where("unionId='$unionId'")->field('uid')->find();
            if ($wash_user) {
                //更新用户信息
                $info['nickName'] = $data['nickName'];
                $info['gender'] = $data['gender'];
                $info['avatarUrl'] = $data['avatarUrl'];
                $info['update_time'] = date('Y-m-d H:i:s');
                $edit_wash_user = $db_wash_user->where("unionId='$unionId'")->setField($info);
                if(!$edit_wash_user){
                    $de_res['msg'] = '更新用户信息失败';
                    $de_res['error'] = 402;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }

                $de_res['data']['uid'] = $wash_user['uid'];
            } else {
                //新增用户信息
                $uid = date('YmdHis').mt_rand(10000, 99999);
                $info['uid'] = $uid;
                $info['nickName'] = $data['nickName'];
                $info['gender'] = $data['gender'];
                $info['avatarUrl'] = $data['avatarUrl'];
                $info['openId'] = $data['openId'];
                $info['unionId'] = $data['unionId'];
                $info['c_list'] = '[]';
                $info['comment_report_list'] = '[]';
                $info['comment_praise_list'] = '[]';
                $info['reply_report_list'] = '[]';
                $info['reply_praise_list'] = '[]';
                $info['create_time'] = date('Y-m-d H:i:s');
                $info['update_time'] = date('Y-m-d H:i:s');
                $add_wash_user = $db_wash_user->data($info)->add();
                if ($add_wash_user) {
                    $de_res['data']['uid'] = $uid;
                }else{
                    $de_res['msg'] = '用户信息添加失败';
                    $de_res['error'] = 402;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }
        } else {
//            print($errCode . "\n");
            $de_res['msg'] = '授权登录错误';
            $de_res['error'] = $errCode;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);
//        error_log('en_res='.$en_res."\n", 3, "test.log");//打印日志

        echo $en_res;
    }

    /**
     * SFA商品列表接口
     *
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      id:分类编号
     *      name:分类名
     *      list:
     *          p_id:SFA产品编号
     *          name:商品展示名
     *          img_url:商品图片链接
     */
    public function sfa_product_list(){
        $db_wash_consumer_class = M('wash_consumer_class');//实例化SFA商品分类列表
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $wash_consumer_class = $db_wash_consumer_class->field('id,name,p_list')->select();

        $arr = array();
        if($wash_consumer_class){
            foreach ($wash_consumer_class as $v){
                $arr_class = array();
                $arr_class['id'] = $v['id'];
                $arr_class['name'] = $v['name'];
                $list = json_decode($v['p_list'], true);
                $arr_class['list'] = array();
                if(!empty($list)){
                    foreach ($list as $lv){
                        $pid = $lv;
                        $wash_consumer_product = $db_wash_consumer_product->where("id='$pid' AND status=1")->field('p_id,name,img_url')->find();
                        if($wash_consumer_product){
                            $wash_consumer_product['count'] = 0;
                            array_push($arr_class['list'],$wash_consumer_product);
                        }
                    }
                }
                array_push($arr,$arr_class);
            }
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * SFA商品同步接口
     * string  p_name   产品名
     * string  p_id     产品编号
     * int     status   状态 1有效 0无效 2挂起
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function sfa_product(){
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表
        $db_wash_consumer_class = M('wash_consumer_class');//实例化SFA商品分类列表

        //返回值数组
        $de_res = array('msg'=>'同步成功', 'error'=> 0, 'data'=> array());

        $post = file_get_contents('php://input');
//        error_log('$post='.$post."\n", 3, "test.log");//打印日志
        $post = json_decode($post, true);

        $p_id = $post['p_id'];
//        error_log('$p_id='.$p_id."\n", 3, "test.log");//打印日志
        if(strlen($p_id) == 0){
            $de_res['msg'] = '缺少产品编号参数';
            $de_res['error'] = 4001;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $p_name = $post['p_name'];
//        error_log('$p_name='.$p_name."\n", 3, "test.log");//打印日志
        if(strlen($p_name) == 0){
            $de_res['msg'] = '缺少产品名称参数';
            $de_res['error'] = 4001;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $status = $post['status'];
//        error_log('$status='.$status."\n", 3, "test.log");//打印日志
        if(strlen($status) == 0){
            $de_res['msg'] = '缺少状态参数';
            $de_res['error'] = 4001;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $wash_consumer_product = $db_wash_consumer_product->where("p_id='$p_id'")->field('id,p_name,status')->find();
        if($wash_consumer_product){
            //修改产品名
            $info['p_name'] = $p_name;
            $info['status'] = $status;
            $info['time'] = time();
            $info['datetime'] = date('Y-m-d H:i:s');
            $edit_wash_consumer_product = $db_wash_consumer_product->where("p_id='$p_id'")->setField($info);
            if(!$edit_wash_consumer_product){
                $de_res['msg'] = '修改失败';
                $de_res['error'] = 4002;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
            if($status != 1){
                $product_id = $wash_consumer_product['id'];//产品表中的ID
                $wash_consumer_class = $db_wash_consumer_class->field('id,p_list')->select();
                foreach($wash_consumer_class as $class){
                    $class_id = $class['id'];//分类表中的ID
                    $class_p_list = json_decode($class['p_list'], true);
                    if(in_array($product_id,$class_p_list)){
                        $key =  array_search($product_id,$class_p_list);
                        unset($class_p_list[$key]);//删除数组元素
                        $list = [];
                        foreach($class_p_list as $p_l){
                            array_push($list,$p_l);
                        }
                        $where['p_list'] = json_encode($list);
                        $edit_wash_consumer_class = $db_wash_consumer_class->where("id='$class_id'")->setField($where);
                        if(!$edit_wash_consumer_class){
                            $de_res['msg'] = '分类数据修改失败';
                            $de_res['error'] = 4003;
                            $en_res = json_encode($de_res, 320);
                            exit($en_res);
                        }
                    }
                }
            }
        }else{
            //新增产品
            $info['p_id'] = $p_id;
            $info['p_name'] = $p_name;
            $info['status'] = $status;
            $info['time'] = time();
            $info['datetime'] = date('Y-m-d H:i:s');
            $add_wash_consumer_product = $db_wash_consumer_product->data($info)->add();
            if(!$add_wash_consumer_product){
                $de_res['msg'] = '新增失败';
                $de_res['error'] = 4002;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * SFA二维码状态接口
     * string  id   二维码编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function sfa_getQRCodeStatus(){
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.id');
        if(strlen($qrcode_id) == 0){
            $de_res['msg'] = '缺少二维码编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

//        $customerConfirm = $db_wash_consumer_confirm->where("QRcode_id='$id'")->field('id')->find();
//        if(!$customerConfirm){
//            //正式链接
////            $url = "http://bmcrm.bluemoon.com.cn/bmcrm-control/custConfirm/getQRCodeStatus?client=android&cuid=024b86b5-45cc-4d36-a50c-494d764c7802&version=2.4.1&format=json&time=1540363398469&source=sfa&sign=ccd9aea51ed5182484728f9faeb5c393";
//            //测试链接
//            $url = "https://tmallapi.bluemoon.com.cn/bmcrm-control/custConfirm/getQRCodeStatus?client=ios&cuid=78771ECF-8D45-4E16-82AE-DDF0A9C4280F&format=json&sign=455e2b1c29cc7210df943acaa454630e&time=1459999388&version=1.0.0&dataSource=null";
//
//            $data = array('id'=>'https://app1.bluemoon.com.cn/sfa?id='.$id);
////            error_log(date('Y-m-d H:i:s').'-sfa_getQRCodeStatus->data='.json_encode($data, 320)."\n", 3, "test.log");//打印日志
//            $res = $this->sfa_post_curl($url,$data);
////            error_log($id.'-sfa_getQRCodeStatus->res='.$res."\n", 3, "test.log");//打印日志
//            $res_list = json_decode($res, true);
//
//            $de_res['msg'] = $res_list['msg'];
//            $de_res['error'] = $res_list['error'];
//            $de_res['data'] = $res_list['data'];
//
//            //转成json形式
//            //JSON_UNESCAPED_UNICODE = 256
//            //JSON_UNESCAPED_SLASHES = 64
//            $en_res = json_encode($de_res, 320);
//
//            echo $en_res;
//        }else{
//            $de_res['msg'] = '该二维码已确认提交过';
//            $de_res['error'] = 403;
//            $en_res = json_encode($de_res, 320);
//            exit($en_res);
//        }

        $qrcode_info = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->field('status')->find();
        if($qrcode_info){
            $status = $qrcode_info['status'];
            if($status == 1){
                //转成json形式
                //JSON_UNESCAPED_UNICODE = 256
                //JSON_UNESCAPED_SLASHES = 64
                $en_res = json_encode($de_res, 320);

                echo $en_res;
            }elseif($status == 0){
                $de_res['msg'] = '该二维码还未与促销员绑定';
                $de_res['error'] = 4021;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }elseif($status == 2){
                $de_res['msg'] = '该二维码已确认提交过';
                $de_res['error'] = 4022;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }elseif($status == 3){
                $de_res['msg'] = '该二维码已退货';
                $de_res['error'] = 4023;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }else{
                $de_res['msg'] = '二维码状态异常';
                $de_res['error'] = 4024;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }else{
            $de_res['msg'] = '二维码信息不存在';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
    }

    /**
     * SFA消费者确认提交接口
     * string  id   二维码编号
     * string  uid  用户编号
     * string  p_list 商品数组(json格式)
     * 商品数组包含:
     *     string  p_id  商品编号
     *     int     p_num 商品数量
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      空
     */
    public function sfa_customerConfirm(){
        $db_wash_user = M('wash_user');//实例化用户信息表
        $db_wash_consumer_confirm = M('wash_consumer_confirm');//实例化消费者确认提交记录表
        $db_wash_qrcode = M('wash_qrcode');//实例化二维码信息表
        $db_wash_pici = M('wash_pici');//实例化二维码批次表
        $db_wash_qy_user = M('wash_qy_user');//实例化企业用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $qrcode_id = I('post.id');
        if(strlen($qrcode_id) == 0){
            $de_res['msg'] = '缺少二维码编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $uid = I('post.uid');
        if(strlen($uid) == 0){
            $de_res['msg'] = '缺少用户编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $en_p_list = I('post.p_list');
        if(strlen($en_p_list) == 0){
            $de_res['msg'] = '缺少商品数组';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
//        error_log('$en_p_list='.$en_p_list."\n", 3, "test.log");//打印日志

        $de_p_list = json_decode($en_p_list, true);
        $p_list = array();
        foreach ($de_p_list as $p){
            $p_arr = array();
            $p_arr['p_id'] = $p['p_id'];
            $p_arr['p_num'] = $p['p_num'];
            array_push($p_list, $p_arr);
        }
        $p_list = json_encode($p_list, true);

        $user = $db_wash_user->where("uid='$uid'")->field('nickName,gender')->find();
        if(!$user){
            $de_res['msg'] = '未查到用户信息';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $qrcode_info = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->field('p_id,pici_id,status,qy_uid')->find();
        if($qrcode_info){
            $status = $qrcode_info['status'];
            if($status == 1){
                $qy_uid = $qrcode_info['qy_uid'];
                $qy_userinfo = $db_wash_qy_user->where("userid='$qy_uid'")->field('name')->find();
                if($qy_userinfo){
                    $p_id = $qrcode_info['p_id'];
                    $pici_id = $qrcode_info['pici_id'];
                    //更新二维码信息表
                    $info['status'] = 2;
                    $info['uid'] = $uid;
                    $info['tijiao_time'] = date('Y-m-d H:i:s');
                    $info['update_time'] = date('Y-m-d H:i:s');
                    $edit_wash_qrcode = $db_wash_qrcode->where("qrcode_id='$qrcode_id'")->setField($info);
                    if(!$edit_wash_qrcode){
                        $de_res['msg'] = '更新二维码信息失败';
                        $de_res['error'] = 4031;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                    //更新二维码批次表
                    $pici_info['update_time'] = date('Y-m-d H:i:s');
                    $edit_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setField($pici_info);
                    if(!$edit_wash_pici){
                        $de_res['msg'] = '更新批次信息失败';
                        $de_res['error'] = 4032;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                    $inc_wash_pici = $db_wash_pici->where("p_id='$p_id' AND pici_id='$pici_id'")->setInc('xiaofei_num');
                    if(!$inc_wash_pici){
                        $de_res['msg'] = '更新批次信息失败';
                        $de_res['error'] = 4033;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }

                    $staff_name = $qy_userinfo['name'];
                    //写入消费者提交记录表
                    $info['QRcode_id'] = $qrcode_id;
                    $info['uid'] = $uid;
                    $info['p_list'] = $p_list;
                    $info['staff_uid'] = $qy_uid;
                    $info['staff_name'] = $staff_name;
                    $info['time'] = time();
                    $info['datetime'] = date('Y-m-d H:i:s');
                    $add_wash_consumer_confirm = $db_wash_consumer_confirm->data($info)->add();
                    if(!$add_wash_consumer_confirm){
                        $de_res['msg'] = '消费者确认提交信息写入失败';
                        $de_res['error'] = 4024;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }

                    //转成json形式
                    //JSON_UNESCAPED_UNICODE = 256
                    //JSON_UNESCAPED_SLASHES = 64
                    $en_res = json_encode($de_res, 320);

                    echo $en_res;
                }else{
                    $de_res['msg'] = '企业员工信息异常';
                    $de_res['error'] = 4023;
                    $en_res = json_encode($de_res, 320);
                    exit($en_res);
                }
            }else{
                $de_res['msg'] = '二维码状态异常';
                $de_res['error'] = 4022;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }else{
            $de_res['msg'] = '该二维码已确认提交过';
            $de_res['error'] = 4021;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
    }

    /**
     * SFA消费者获取保单
     * string  id      二维码编号
     * string  name    姓名
     * int     gender  性别 1男2女
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      staff:
     *          name      促销员姓名
     *          position  促销员职位
     *          avatar    促销员头像
     *          qr_code   促销员名片二维码
     *      bd_img_url: 保单链接
     *      bd_num: 保单编号
     */
    public function sfa_customer_receive_baodan(){
        $db_wash_consumer_confirm = M('wash_consumer_confirm');//实例化消费者确认提交记录表
        $db_wash_baodan_record = M('wash_baodan_record');//实例化消费者保单信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $QRcode_id = I('post.id');
        if(strlen($QRcode_id) == 0){
            $de_res['msg'] = '缺少二维码编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $name = I('post.name');
        if(strlen($name) == 0){
            $de_res['msg'] = '缺少消费者姓名';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        $gender = I('post.gender');
        if(strlen($gender) == 0){
            $de_res['msg'] = '缺少消费者性别';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        if($gender == 1){
            $gender_name = ' 先生';
        }elseif($gender == 2){
            $gender_name = ' 女士';
        }else{
            $gender_name = ' 先生/女士';
        }

        //查询是否已经有生成保单记录
        $cord = $db_wash_baodan_record->where("QRcode_id='$QRcode_id'")->field('id')->find();
        if($cord){
            $de_res['msg'] = '已经生成过保单';
            $de_res['error'] = 42499;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //查询购买记录
        $record = $db_wash_consumer_confirm->where("QRcode_id='$QRcode_id'")->field('p_list,staff_uid,staff_store,datetime')->find();
        if(!$record){
            $de_res['msg'] = '未查到购买记录';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        /*消费者信息*/
        $userInfo['name'] = $name;
        $userInfo['gender'] = $gender;
        $userInfo['name_gender'] = $name.$gender_name;

        /*促销员信息*/
        $staff_uid = $record['staff_uid'];
        $staff_info = $this->getQiYeUserInfo($staff_uid);
        if($staff_info['errcode'] != 0){
            $de_res['msg'] = $staff_info['errmsg'];
            $de_res['error'] = $staff_info['errcode'];
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $orderInfo['name'] = $staff_info['name'];
        $orderInfo['p_list'] = json_decode($record['p_list'], true);
        $orderInfo['staff_store'] = $record['staff_store'];
        $orderInfo['datetime'] = $record['datetime'];
        $orderInfo['qr_code'] = $staff_info['qr_code'];

        /*保单编号*/
        $bd_num = 'BMBD'.date('Ymd').mt_rand(10000,99999);

        /*生成保单图*/
        $bd_img_url = $this->zhibao_image($userInfo,$orderInfo,$bd_num);

        //写入保单信息表
        $info['QRcode_id'] = $QRcode_id;
        $info['bd_num'] = $bd_num;
        $info['name'] = $name;
        $info['gender'] = $gender;
        $info['time'] = time();
        $info['datetime'] = date('Y-m-d H:i:s');
        $add_wash_baodan_record = $db_wash_baodan_record->data($info)->add();
        if(!$add_wash_baodan_record){
            $de_res['msg'] = '保单信息表写入失败';
            $de_res['error'] = 403;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['data']['staff']['name'] = $staff_info['name'];
        $de_res['data']['staff']['position'] = $staff_info['position'];
        $de_res['data']['staff']['avatar'] = $staff_info['avatar'];
        $de_res['data']['staff']['qr_code'] = $staff_info['qr_code'];

        $de_res['data']['bd_img_url'] = $bd_img_url['save_url'];
        $de_res['data']['bd_num'] = $bd_num;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * SFA消费者分享保单
     * string  bd_num  保单编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      bd_img_url: 保单链接
     *      bd_num: 保单编号
     */
    public function sfa_customer_share_baodan(){
        $db_wash_consumer_confirm = M('wash_consumer_confirm');//实例化消费者确认提交记录表
        $db_wash_baodan_record = M('wash_baodan_record');//实例化消费者保单信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $bd_num = I('post.bd_num');
        if(strlen($bd_num) == 0){
            $de_res['msg'] = '缺少保单编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
        //查询是否已经有生成保单记录
        $bd_cord = $db_wash_baodan_record->where("bd_num='$bd_num'")->field('QRcode_id,name,gender')->find();
        if(!$bd_cord){
            $de_res['msg'] = '未查到保单记录';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
//        error_log('$bd_cord='.json_encode($bd_cord, true)."\n", 3, "test.log");//打印日志

        $QRcode_id = $bd_cord['QRcode_id'];
        $name = '客户';
        $gender = $bd_cord['gender'];
        if($gender == 1){
            $gender_name = ' 先生';
        }elseif($gender == 2){
            $gender_name = ' 女士';
        }else{
            $gender_name = ' 先生/女士';
        }

        //查询购买记录
        $record = $db_wash_consumer_confirm->where("QRcode_id='$QRcode_id'")->field('p_list,staff_uid,staff_store,datetime')->find();
        if(!$record){
            $de_res['msg'] = '未查到购买记录';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
//        error_log('$record='.json_encode($record, true)."\n", 3, "test.log");//打印日志

        /*消费者信息*/
        $userInfo['name'] = $name;
        $userInfo['gender'] = $gender;
        $userInfo['name_gender'] = $name.$gender_name;

        /*促销员信息*/
        $staff_uid = $record['staff_uid'];
        $staff_info = $this->getQiYeUserInfo($staff_uid);
        if($staff_info['errcode'] != 0){
            $de_res['msg'] = $staff_info['errmsg'];
            $de_res['error'] = $staff_info['errcode'];
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }
//        error_log('$staff_info='.json_encode($staff_info, true)."\n", 3, "test.log");//打印日志

        $orderInfo['name'] = $staff_info['name'];
        $orderInfo['p_list'] = json_decode($record['p_list'], true);
        $orderInfo['staff_store'] = $record['staff_store'];
        $orderInfo['datetime'] = $record['datetime'];
        $orderInfo['qr_code'] = $staff_info['qr_code'];

        /*生成保单图*/
        $bd_img_url = $this->zhibao_image($userInfo,$orderInfo,$bd_num);

        $de_res['data']['bd_img_url'] = $bd_img_url['save_url'];
        $de_res['data']['bd_num'] = $bd_num;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * SFA消费者购买记录
     * string  uid  用户编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      staff_store  购买门店
     *      staff_brand  门店品牌
     *      staff_name   促销员姓名
     *      staff_phone  促销员电话
     *      staff_wx     促销员微信
     *      staff_level  促销员等级
     *      time         时间戳
     *      datetime     时间
     *      p_list 商品数组(json格式)
     *          string  name   商品展示名
     *          int     p_id   商品编号
     *          int     p_num  商品数量
     */
    public function sfa_customer_buy_record(){
        $db_wash_user = M('wash_user');//实例化用户信息表
        $db_wash_consumer_confirm = M('wash_consumer_confirm');//实例化消费者确认提交记录表
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $uid = I('post.uid');
        if(strlen($uid) == 0){
            $de_res['msg'] = '缺少用户编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $user = $db_wash_user->where("uid='$uid'")->field('id')->find();
        if(!$user){
            $de_res['msg'] = '未查到用户信息';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $arr = array();
        $record = $db_wash_consumer_confirm->where("uid='$uid'")->field('p_list,staff_name,staff_level,staff_phone,staff_wx,staff_store,staff_brand,time')->select();
        if($record){
            foreach($record as $cord){
                $p_list = json_decode($cord['p_list'], true);
                foreach($p_list as $k=>$p){
                    $p_id = $p['p_id'];
                    $p_info = $db_wash_consumer_product->where("p_id='$p_id'")->field('name')->find();
                    if(!$p_info){
                        $de_res['msg'] = '未查到商品信息';
                        $de_res['error'] = 401;
                        $en_res = json_encode($de_res, 320);
                        exit($en_res);
                    }
                    $p_list[$k]['name'] = $p_info['name'];
                }
                $cord['p_list'] = $p_list;
                $cord['datetime'] = date('Y-m-d',$cord['time']);
                array_push($arr, $cord);
            }
        }

        $de_res['data'] = $arr;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * SFA获取企业微信促销员信息接口
     * string  id  二维码编号
     *
     * @return array
     * msg:
     *      提示信息
     * error:
     *      0成功，>0错误码
     * data:
     *      name      促销员姓名
     *      position  促销员职位
     *      avatar    促销员头像
     *      qr_code   促销员名片二维码
     */
    public function sfa_salesperson_info(){
        $db_wash_consumer_confirm = M('wash_consumer_confirm');//实例化消费者确认提交记录表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $QRcode_id = I('post.id');
        if(strlen($QRcode_id) == 0){
            $de_res['msg'] = '缺少二维码编号';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //查询购买记录
        $record = $db_wash_consumer_confirm->where("QRcode_id='$QRcode_id'")->field('staff_uid')->find();
        if(!$record){
            $de_res['msg'] = '未查到购买记录';
            $de_res['error'] = 401;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        /*促销员信息*/
        $staff_uid = $record['staff_uid'];
        $staff_info = $this->getQiYeUserInfo($staff_uid);
        if($staff_info['errcode'] != 0){
            $de_res['msg'] = $staff_info['errmsg'];
            $de_res['error'] = $staff_info['errcode'];
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $de_res['data']['staff']['name'] = $staff_info['name'];
        $de_res['data']['staff']['position'] = $staff_info['position'];
        $de_res['data']['staff']['avatar'] = $staff_info['avatar'];
        $de_res['data']['staff']['qr_code'] = $staff_info['qr_code'];

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * SFA项目对接curl的POST请求
     * @param String $url     请求地址
     * @param Array  $data    POST数据
     *
     * @return String
     */
    public function sfa_post_curl($url, $data){
        $headers = array(
            "Content-type: application/json;charset='utf-8'",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache"
        );
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); //设置超时
        if(0 === strpos(strtolower($url), 'https')) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data, true));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $res = curl_exec($ch);//CURLOPT_RETURNTRANSFER 不设置  curl_exec返回TRUE 设置  curl_exec返回json(此处) 失败都返回FALSE
        curl_close($ch);

        return $res;
    }

    /**
     * 网页授权获取微信用户信息
     * string  code  Code参数
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      uid 用户识别唯一ID
     */
    public function getWeiXinUserInfo(){
        $db_wash_user = M('wash_user');//实例化用户信息表

        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        $code = I('post.code');
//        error_log('code='.$code."\n", 3, "test.log");//打印日志
        if(!$code){
            $de_res['msg'] = '缺少code参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $this->wx_appid . '&secret=' . $this->wx_secret . '&code=' . $code . '&grant_type=authorization_code';
        $access_token_str = $this->curl_get($get_token_url);
//        error_log('$access_token_str='.$access_token_str."\n", 3, "test.log");//打印日志
        $access_token_list = json_decode($access_token_str, true);
        if (!$access_token_list['access_token']) {
            $de_res['msg'] = $access_token_list['errmsg'];
            $de_res['error'] = $access_token_list['errcode'];
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        //获取access_token
        $access_token = $access_token_list['access_token'];
//        error_log('access_token='.$access_token."\n", 3, "test.log");//打印日志
        //获取openid
        $openid = $access_token_list['openid'];
//        error_log('openid='.$openid."\n", 3, "test.log");//打印日志

        //获取微信用户信息
        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user_msg_str = $this->curl_get($get_user_info_url);
//        error_log('user_msg_str='.$user_msg_str."\n", 3, "test.log");//打印日志
        $user_msg_list = json_decode($user_msg_str, true);
        //当用户信息获取为空时，不存session(修复刷新后不能获取到用户信息的BUG)
        if(!$user_msg_list['unionid']){
            $de_res['msg'] = '缺少unionid参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        $unionId = $user_msg_list['unionid'];
//        error_log('unionid='.$unionId."\n", 3, "test.log");//打印日志
        $wash_user = $db_wash_user->where("unionId='$unionId'")->field('uid')->find();
        if ($wash_user) {
            $de_res['data']['uid'] = $wash_user['uid'];
        } else {
            $uid = date('YmdHis').mt_rand(10000, 99999);
            $info['uid'] = $uid;
            $info['nickName'] = $user_msg_list['nickname'];
            $info['gender'] = $user_msg_list['sex'];
            $info['avatarUrl'] = $user_msg_list['headimgurl'];
            $info['openId'] = $user_msg_list['openid'];
            $info['unionId'] = $user_msg_list['unionid'];
            $info['c_list'] = '[]';
            $info['comment_report_list'] = '[]';
            $info['comment_praise_list'] = '[]';
            $info['reply_report_list'] = '[]';
            $info['reply_praise_list'] = '[]';
            $add_wash_user = $db_wash_user->data($info)->add();
            if ($add_wash_user) {
                $de_res['data']['uid'] = $uid;
            }else{
                $de_res['msg'] = '用户信息添加失败';
                $de_res['error'] = 402;
                $en_res = json_encode($de_res, 320);
                exit($en_res);
            }
        }

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);
//        error_log('en_res='.$en_res."\n", 3, "test.log");//打印日志

        echo $en_res;
    }

    /**
     * 获取企业微信用户信息接口
     * string  UserId  企业微信用户ID
     *
     * @return array  用户信息列表
     */
    public function getQiYeUserInfo($UserId){
        $access_token = $this->getAccessToken();
//        error_log($access_token."\n", 3, "test.log");//打印日志

        //获取成员信息
        $get_user_info_url = 'https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$access_token.'&userid='.$UserId;
        $code_str = $this->curl_get($get_user_info_url);
//        error_log($code_str."\n", 3, "test.log");//打印日志
        $code_list = json_decode($code_str, true);

        return $code_list;
    }

    /**
     * 微信H5分享-JS-SDK使用权限签名接口
     * string  url  当前链接的url
     *
     * @return array
     * msg: 错误信息
     * error:
     *      0成功，>0错误码
     * data:
     *      签名数组
     */
    public function jsapi_ticket(){
        //返回值数组
        $de_res = array('msg'=>'', 'error'=> 0, 'data'=> array());

        //注意:URL一定要动态获取，不能hardcode
        $url = I('post.url');
//        error_log('$url='.$url."\n", 3, "test.log");//打印日志
        if(!$url){
            $de_res['msg'] = '缺少url参数';
            $de_res['error'] = 400;
            $en_res = json_encode($de_res, 320);
            exit($en_res);
        }

        /*获取access_token*/
        if(!$_SESSION['jsapi']['access_token'] && $_SESSION['jsapi']['expire_time']<time()){//如果access_token不存在或者已经过期，重新取access_token
            $get_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->wx_appid."&secret=".$this->wx_secret;
            $res = $this->curl_get($get_token_url);
//            error_log('$access_token='.$res."\n", 3, "test.log");//打印日志
            $r = json_decode($res, true);

            $access_token = $r['access_token'];
            //将重新获取到的aceess_token存到session
            $_SESSION['jsapi']['access_token'] = $access_token;
            $_SESSION['jsapi']['expire_time'] = time() + 7000;

            /*获取jsapi_ticket*/
            $jsapi_ticket_url='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$_SESSION['jsapi']['access_token'].'&type=jsapi';
            $res = $this->curl_get($jsapi_ticket_url);
//            error_log('$jsapi_ticket='.$res."\n", 3, "test.log");//打印日志
            $result = json_decode($res, true);

            $jsapi_ticket = $result['ticket'];
            //将重新获取到的jsapi_ticket存到session
            $_SESSION['jsapi']['jsapi_ticket'] = $jsapi_ticket;
        }

        /*生成签名*/
        $jsapiTicket = $_SESSION['jsapi']['jsapi_ticket'];
//        error_log('$_SESSION='.json_encode($_SESSION, true)."\n", 3, "test.log");//打印日志

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
//        error_log('$jsapi_ticket='.$jsapiTicket."\n", 3, "test.log");//打印日志
//        error_log('$nonceStr='.$nonceStr."\n", 3, "test.log");//打印日志
//        error_log('$timestamp='.$timestamp."\n", 3, "test.log");//打印日志
//        error_log('$url='.$url."\n", 3, "test.log");//打印日志
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
//        error_log('$string='.$string."\n", 3, "test.log");//打印日志
        $signature = sha1($string);
//        error_log('$signature='.$signature."\n", 3, "test.log");//打印日志

        $signPackage = array(
            "appid"     => $this->wx_appid,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );

        $de_res['data'] = $signPackage;

        //转成json形式
        //JSON_UNESCAPED_UNICODE = 256
        //JSON_UNESCAPED_SLASHES = 64
        $en_res = json_encode($de_res, 320);

        echo $en_res;
    }

    /**
     * JS-SDK签名用于生成随机字符串
     */
    public function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * 生成质保图
     * array   $userInfo   消费者信息数组
     * array   $orderInfo  促销员信息数组
     * string  $bd_num     保单编号
     *
     * @return array
     * data:
     *      save_url  保单图片链接地址
     */
    public function zhibao_image($userInfo,$orderInfo,$bd_num){
        $db_wash_consumer_product = M('wash_consumer_product');//实例化SFA商品列表
        $image = new \Think\Image();

        //判断文件路径是否存在
        if(!is_dir("./Uploads/QiYe/safe"))
        {
            mkdir("./Uploads/QiYe/safe"); //新建目录
        }

        /*总图*/
        $total_p_num = 0;//提交的总产品数
        $p_list = $orderInfo['p_list'];
        foreach($p_list as $k=>$p){
            $p_id = $p['p_id'];
            $p_info = $db_wash_consumer_product->where("p_id='$p_id'")->field('name')->find();
            if($p_info){
                $p_list[$k]['name'] = $p_info['name'];
            }
            if($p['p_num']){
                $total_p_num += $p['p_num'];
            }
        }

        //设置总高度
        $t_height = 1193 + 26 + count($p_list) * 60 + 500;
        $t_width = 705;
        //创建图片
        $save_name = './Uploads/QiYe/safe/'.$bd_num.'.png';
        $this->create_img($t_width,$t_height,$save_name);

        //打印产品名称
        $image->open($save_name)->text('产品名称:','./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(35,1219))->save($save_name);
        //循环打印产品信息
        $xd_height = 0;
        foreach($p_list as $product){
            $image->open($save_name)->text($product['name'],'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(167,1219+$xd_height))->save($save_name);
            $image->open($save_name)->text('x'.$product['p_num'],'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(629,1219+$xd_height))->save($save_name);
            $xd_height += 63;
        }

        /*分图一*/
//        $username = $userInfo['name'];
        $username = $userInfo['name_gender'];
        $store = $orderInfo['staff_store'];
        $img1 = './Uploads/QiYe/safe/IMG1-'.time().mt_rand(10000,99999).'.png';
        //添加水印文字并另存
        $image->open('./Uploads/QiYe/base/base_1.png')->text($bd_num,'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#979797',array(148,52))->save($img1);
        $image->open($img1)->text($username,'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#636363',array(125,250))->save($img1);
        $image->open($img1)->text($store,'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(167,1151))->save($img1);

        /*分图二*/
        $img2 = './Uploads/QiYe/safe/IMG2-'.time().mt_rand(10000,99999).'.png';
        $datetime = $orderInfo['datetime'];
        $total_after_num = $total_p_num * 3;
        $total_after_time = "+".$total_after_num." months";
        $datetime_after = date("Y-m-d H:i:s", strtotime($total_after_time, strtotime($orderInfo['datetime'])));
        $order_name = $orderInfo['name'];

        //获取二维码
        $img_url = $orderInfo['qr_code'];
        $QR = './Uploads/QiYe/safe/QR-'.time().mt_rand(10000,99999).'.png';//文件名称生成;
        $this->img_exists($img_url,$QR);

        //添加水印文字并另存
        $image->open('./Uploads/QiYe/base/base_2.png')->text($datetime,'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(220,170))->save($img2);
        $image->open($img2)->text($datetime_after,'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(220,230))->save($img2);
        $image->open($img2)->text($order_name,'./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#343434',array(220,290))->save($img2);
        //添加水印图片并另存
        $image->open($img2)->water($QR,array(500,139),100)->save($img2);

        /*合成*/
        $image->open($save_name)->water($img1,array(0,0),100)->save($save_name);
        $image->open($save_name)->water($img2,array(0,$t_height-500),100)->save($save_name);

        /*清除素材图*/
        unlink($img1);
        unlink($QR);
        unlink($img2);

        //生成图片链接地址
        $save_url = '/wash_helper/Uploads/QiYe/safe/'.$bd_num.'.png';

        $arr['save_url'] = $save_url;
        return $arr;
    }

    /**
     * 创建图片
     * int     width    宽
     * int     height   高
     * string  saveImg  存储地址
     */
    public function create_img($width,$height,$saveImg){
        //创建画布
        $img = imagecreatetruecolor($width,$height);
        //背景色
        $bg_color = imagecolorallocate($img,255,255,255);
        //在画布上染色
        imagefill($img,0,0,$bg_color);
        //输出图像
        imagepng($img,$saveImg);
        //释放画布资源
        imagedestroy($img);
    }

    /**
     * 网络图片保存到本地
     * string  url  网络图片地址
     * string  filename  存储地址
     */
    public function img_exists($url,$filename){
        $state = @file_get_contents($url,0,null,0,1);//获取网络资源的字符内容
        if($state){
            ob_start();//打开输出
            readfile($url);//输出图片文件
            $img = ob_get_contents();//得到浏览器输出
            ob_end_clean();//清除输出并关闭
            $fp = @fopen($filename, "a");
            fwrite($fp, $img);//向当前目录写入图片文件，并重新命名
            fclose($fp);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取企业微信access_token
     */
    public function getAccessToken(){
        $code_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$this->corpid."&corpsecret=".$this->corpsecret;
        $access_token_str = $this->curl_get($code_url);
        $access_token_list = json_decode($access_token_str, true);
        if ($access_token_list['errcode'] == 0) {
            return $access_token_list["access_token"];
        }
        return false;
    }

    /**
     * 数组分页函数(核心函数 array_slice)
     * 用此函数之前要先将数据库里面的所有数据按一定的顺序查询出来存入数组中
     * $count  每页多少条数据
     * $page   当前第几页
     * $array  查询出来的所有数组
     * order   0-不变 1-反序
     */
    public function page_array($count,$page,$array,$order){
        global $countpage; #定全局变量
        $page=(empty($page))?'1':$page; #判断当前页面是否为空 如果为空就表示为第一页面
        $start=($page-1)*$count; #计算每次分页的开始位置
        if($order==1){
            $array=array_reverse($array);
        }
        $totals=count($array);
        $countpage=ceil($totals/$count); #计算总页面数
        $pagedata=array();
        $pagedata=array_slice($array,$start,$count);
        return $pagedata;  #返回查询数据
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData($encryptedData, $iv, $session_key, &$data){
        if (strlen($session_key) != 24) {
            return -41001;
        }
        $aesKey=base64_decode($session_key);

        if (strlen($iv) != 24){
            return -41002;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);
        $result=openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

//        error_log('result='.$result."\n", 3, "test.log");//打印日志

        $dataObj=json_decode($result);
        if( $dataObj  == NULL )
        {
            return -41003;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return -41003;
        }

        $data = $result;
        return 0;
    }

    /**
     * 调用curl
     * $url   接口url   string
     * $type  请求类型  string
     * $res   返回类型  string
     * $arr   请求参数  string
     */
    public function http_curl($url,$type = 'get',$res = 'json',$arr = ''){
        //1.初始化curl
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        if($type == 'post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        //3.采集
        $output = curl_exec($ch);
        //4.关闭
        curl_close($ch);
        if($res == 'json'){
            if(curl_error($ch)){
                //请求失败，返回错误信息
                return curl_error($ch);
            }else{
                //请求成功，返回数据
                return json_decode($output,true);
            }
        }
    }

    /**
     * curl get方式
     * string  url    链接地址
     */
    public function curl_get($url){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    /**
     * curl post方式
     * string  url    链接地址
     * array   param  数组array("key1" => $value1, "key2" => $value2);
     */
    public function curl_post($url, $param){
        $param = json_encode($param,true);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $data = curl_exec($ch);
        return $data;
    }

    /**
     * 测试调试专用
     */
    public function index(){
        /*--------------------------测试开始--------------------------*/

//        //测试链接
//        $url = "https://tmallapi.bluemoon.com.cn/bmcrm-control/custConfirm/customerConfirm?client=ios&cuid=78771ECF-8D45-4E16-82AE-DDF0A9C4280F&format=json&sign=455e2b1c29cc7210df943acaa454630e&time=1459999388&version=1.0.0&dataSource=null";
//
//        $p_list = array(
//            0 => array(
//                'p_id'=>'C10060111',
//                'p_num'=>2
//            ),
//            1 => array(
//                'p_id'=>'C10060115',
//                'p_num'=>1
//            ),
//            2 => array(
//                'p_id'=>'C10060117',
//                'p_num'=>3
//            )
//        );
//
//        $data = array(
//            'uid'=> '2018111311103898695',
//            'id'=>'https://app1.bluemoon.com.cn/sfa?id=A295B0DE65ACB0224',
//            'nick'=>'洋',
//            'gender'=>1,
//            'p_list'=>$p_list
//        );
//
//        echo json_encode($data,320);

//        $res = $this->sfa_post_curl($url,$data);
//        error_log('$confirm->res='.$res."\n", 3, "test.log");//打印日志

//        $image = new \Think\Image();

//        //判断文件路径是否存在
//        if(!is_dir("./Uploads/QiYe/safe"))
//        {
//            mkdir("./Uploads/QiYe/safe"); //新建目录
//        }

//        $img1 = './Uploads/QiYe/base/base_1.png';
//        $img2 = './Uploads/QiYe/base/base_2.png';
//
//        $save_file = './Uploads/QiYe/safe/test.png';
//        $this->create_img(705,2000,$save_file);


//        $locate1 = array(0,0);//坐标位置
//        $image->open($save_file)->water($img1,$locate1,100)->save($save_file);
//        $locate2 = array(0,1500);//坐标位置
//        $image->open($save_file)->water($img2,$locate2,100)->save($save_file);


//        $locate1 = array(0,0);//坐标位置
//        // 在图片上添加水印图片并另存
//        $image->open('./Uploads/QiYe/base/base_1.png')->water('./logo.png',$locate1,100)->save("./Uploads/QiYe/safe/water.png");
//        $locate2 = array(200,600);//坐标位置
//        // 在图片上添加水印文字并另存
//        $image->open('./Uploads/QiYe/safe/water.png')->text('LYliuyang@qq.com刘洋123','./ThinkPHP/Library/Think/QiYe/ttfs/pfht-zhun-jian.ttf',20,'#000000',$locate2)->save("./Uploads/QiYe/safe/water.png");


//        $url = 'https://open.work.weixin.qq.com/wwopen/userQRCode?vcode=vc951b645a03d17d1b';
//        $filename = './Uploads/QiYe/safe/QRcode.png';//文件名称生成;
//        $this->img_exists($url,$filename);

        /*--------------------------测试结束--------------------------*/
    }
}